package com.pucong.gitee.database.backup.database.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pucong.gitee.database.backup.common.entity.BackupDatabase;
import com.pucong.gitee.database.backup.common.entity.ServiceComputer;
import com.pucong.gitee.database.backup.common.selfenum.ServiceType;
import com.pucong.gitee.database.backup.common.selfenum.TreeType;
import com.pucong.gitee.database.backup.common.vo.DbBackTree;
import com.pucong.gitee.database.backup.configuration.exception.BusinessException;
import com.pucong.gitee.database.backup.database.mapper.BackupDatabaseMapper;
import com.pucong.gitee.database.backup.database.mapper.BackupExeSqlLogMapper;
import com.pucong.gitee.database.backup.database.util.BackupService;
import com.pucong.gitee.database.backup.database.util.BackupServiceFactory;
import com.pucong.gitee.database.backup.database.vo.DeleteDatabase;
import com.pucong.gitee.database.backup.database.vo.ExeSqlResult;
import com.pucong.gitee.database.backup.database.vo.RenameDatabase;
import com.pucong.gitee.database.backup.service.mapper.ServiceComputerMapper;
import com.pucong.gitee.database.backup.utils.UUID;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.*;


/**
 * 人员表 service实现类
 *
 * @author pucong
 * @company www.louddt.com
 * @create 2020-06-23
 */
@Service
public class BackupDatabaseServiceImpl implements BackupDatabaseService {

    @Autowired
    private BackupDatabaseMapper backupDatabaseMapper;

    @Autowired
    private DatabaseStaticService databaseStaticService;

    @Autowired
    private BackupExeSqlLogMapper backupExeSqlLogMapper;

    @Autowired
    private ServiceComputerMapper serviceComputerMapper;

    @Override
    public IPage<BackupDatabase> getDatabaseListByPage(int pageNum, int pageSize, BackupDatabase backupDatabase) {
        Page<BackupDatabase> page = new Page<>(pageNum, pageSize);
        //构造分页查询
        LambdaQueryWrapper<BackupDatabase> params = new LambdaQueryWrapper<>();
        params.eq(StringUtils.isNotBlank(backupDatabase.getId()),BackupDatabase::getId,backupDatabase.getId())
                .eq(StringUtils.isNotBlank(backupDatabase.getDatabaseName()),BackupDatabase::getDatabaseName,backupDatabase.getDatabaseName());

        params.orderByDesc(BackupDatabase::getCreateTime);
        IPage<BackupDatabase> backupDatabaseIPage = backupDatabaseMapper.selectPage(page, params);
        return backupDatabaseIPage;
    }

    @Override
    public List<BackupDatabase> getDatabaseList() {
        List<BackupDatabase> backupDatabases = backupDatabaseMapper.selectList(null);
        return backupDatabases;
    }

    @Override
    public BackupDatabase getBaseInfoById(String id) {
        return backupDatabaseMapper.selectById(id);
    }

    @Override
    public int saveBaseInfo(BackupDatabase backupDatabase) {
        if(StringUtils.isBlank(backupDatabase.getId())){
            backupDatabase.setId(UUID.uuid());
            backupDatabase.setCreateTime(new Date());
            backupDatabaseMapper.insert(backupDatabase);
        }else{
            backupDatabase.setCreateTime(null);
            backupDatabaseMapper.updateById(backupDatabase);
        }
        return 1;
    }

    @Override
    public boolean connectionTest(BackupDatabase backupDatabase) {
        BackupServiceFactory backupServiceFactory = new BackupServiceFactory();
        BackupService backupService = backupServiceFactory.getBackupService(backupDatabase,backupExeSqlLogMapper);
        Boolean connection = backupService.getConnection();
        backupService.closeAll();
        return connection;
    }

    @Override
    public boolean connectionTestById(String id) {
        BackupDatabase backupDatabase = backupDatabaseMapper.selectById(id);
        if(backupDatabase == null){
            throw new BusinessException("获取数据库异常，未找到数据");
        }
        BackupServiceFactory backupServiceFactory = new BackupServiceFactory();
        BackupService backupService = backupServiceFactory.getBackupService(backupDatabase,backupExeSqlLogMapper);
        Boolean connection = backupService.getConnection();
        backupService.closeAll();
        return connection;
    }

    @Override
    public ExeSqlResult getDatabaseList(String databaseId) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String sessionId = request.getSession().getId();
        BackupService backupService = databaseStaticService.getConnectionById(sessionId, databaseId);
        ExeSqlResult dataBaseList = backupService.getDataBaseList();
        backupService.closeAll();
        return dataBaseList;
    }

    @Override
    public Boolean closeConnection(String databaseId) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String sessionId = request.getSession().getId();
        BackupService backupService = databaseStaticService.getConnectionById(sessionId, databaseId);
        backupService.closeAll();
        return true;
    }

    @Override
    public Boolean renameDatabase(String databaseId, RenameDatabase renameDatabase) {
        BackupService backupService = databaseStaticService.getConnectionById(renameDatabase.getSessionId(), databaseId);
        backupService.renameDatabase(renameDatabase.getDatabaseName(),renameDatabase.getToDatabaseName());
        backupService.closeAll();
        return true;
    }

    @Override
    public Boolean deleteDatabase(String databaseId, DeleteDatabase deleteDatabase) {
        BackupService backupService = databaseStaticService.getConnectionById(deleteDatabase.getSessionId(), databaseId);
        backupService.dropDatabase(deleteDatabase.getDatabaseName());
        backupService.closeAll();
        return true;
    }

    @Override
    public List<DbBackTree> getTreeList(String id, TreeType treeType) {
        if(StringUtils.isBlank(id)){
            // 查询一级列表

        }else{


        }


        // 数据源
        List<BackupDatabase> backupDatabases = backupDatabaseMapper.selectList(null);
        // 服务器
        List<ServiceComputer> serviceComputers = serviceComputerMapper.selectList(null);
        List<DbBackTree> dbBackTreeList = new ArrayList<>();
        for (BackupDatabase backupDatabase : backupDatabases) {
            DbBackTree dbBackTree = new DbBackTree();
            dbBackTree.setId(backupDatabase.getId());
            dbBackTree.setPId("0");
            dbBackTree.setTreeName(backupDatabase.getConnectName());
            dbBackTree.setTreeType(TreeType.数据源);
            dbBackTreeList.add(dbBackTree);
        }
        for (ServiceComputer serviceComputer : serviceComputers) {
            DbBackTree dbBackTree = new DbBackTree();
            dbBackTree.setId(serviceComputer.getId());
            dbBackTree.setPId("0");
            dbBackTree.setTreeName(serviceComputer.getServiceName());
            if(ServiceType.linux == serviceComputer.getServiceType()){
                dbBackTree.setTreeType(TreeType.linux服务器);
            }else{
                dbBackTree.setTreeType(TreeType.Windows服务器);
            }
            dbBackTreeList.add(dbBackTree);
        }
        return dbBackTreeList;
    }
}
